<template>
	<view>
		<view class="container">
			<!-- <search></search> -->
			<view class="row row-underline">
				<view class="item">
					<view class="value"><span class="data">{{ data.line }}</span>条</view>
					<view class="name">线路条数</view>
				</view>
				<view class="space"></view>
				<view class="item">
					<view class="value"><span class="data">{{ data.cableSection }}</span>米</view>
					<view class="name">电缆长度</view>
				</view>
			</view>
			<view class="row row-underline">
				<view class="item">
					<view class="value"><span class="data">{{ data.channelCount }}</span>个</view>
					<view class="name">通道</view>
				</view>
				<view class="space"></view>
				<view class="item">
					<view class="value"><span class="data">{{ parseInt(data.channelLen) }}</span>米</view>
					<view class="name">通道长度</view>
				</view>
			</view>
			<view class="row row-underline">
				<view class="item">
					<view class="value"><span class="data">{{ data.switchStation }}</span>座</view>
					<view class="name">开关站</view>
				</view>
				<view class="space"></view>
				<view class="item">
					<view class="value"><span class="data">{{ data.ringBox }}</span>座</view>
					<view class="name">环网柜</view>
				</view>
			</view>
			<view class="row row-underline">
				<view class="item">
					<view class="value"><span class="data">{{ data.branchBox }}</span>座</view>
					<view class="name">分支箱</view>
				</view>
				<view class="space"></view>
				<view class="item">
					<view class="value"><span class="data">{{ data.electricityRoom }}</span>座</view>
					<view class="name">配电室</view>
				</view>
			</view>

			<view class="row row-underline">
				<view class="item">
					<view class="value"><span class="data">{{ data.compactSubstation }}</span>座</view>
					<view class="name">箱变</view>
				</view>
				<view class="space"></view>
				<view class="item">
					<view class="value"><span class="data">{{ data.cableConnector }}</span>台</view>
					<view class="name">接头数</view>
				</view>
			</view>

			<view class="row row-underline">
				<view class="item">
					<view class="value"><span class="data">{{ data.tower }}</span>基</view>
					<view class="name">杆塔</view>
				</view>
				<view class="space"></view>
				<view class="item">
					<view class="value"><span class="data">{{ data.cableWell }}</span>口</view>
					<view class="name">电缆井</view>
				</view>
			</view>

			<view class="row export-time">数据导出时间：{{ data.exportTime }}</view>
			<view class="row">
				<u-button class="" @click="showZipPath">查看压缩文件放置路径</u-button>
			</view>
			<view class="row">
				<u-button class="" @click="importFileData">导入数据</u-button>
			</view>
			<!-- <view class="row">
				<u-button class="" @click="lineImportData">在线导入数据</u-button>
			</view> -->
			<view class="row">
				<u-button class="" @click="logout">退出登录</u-button>
				<view class="space1"></view>
				<u-button @click="modify" class="modify">修改密码</u-button>
			</view>
			<u-popup :show="show" @close="close" mode="center" :round="10">
				<view style="width: 20rem; padding: 1rem">
					<u--form labelPosition="left" :model="model" class="login-from" ref="form" errorType="toast">
						<view>输入新密码</view>
						<u-form-item class="input-item" label="" labelWidth="0" prop="repassword1" borderBottom
							ref="repassword1">
							<u--input v-model="model.repassword1" type="password" placeholder="输入新密码" border="none"
								clearable></u--input>
						</u-form-item>
						<view>确认密码</view>
						<u-form-item class="input-item" label="" labelWidth="0" prop="repassword2" borderBottom
							ref="repassword2">
							<u--input v-model="model.repassword2" type="password" placeholder="再输入一次确认密码" border="none"
								clearable></u--input>
						</u-form-item>
					</u--form>
					<u-button class="btn" @click="reSubmit">提 交</u-button>
				</view>
			</u-popup>
		</view>
		<u-modal :show="showDirModal" :title="dirModalTitle" :content="dirContent"
			@confirm="showDirModal = false"></u-modal>
		<u-modal :show="showDecompressResult" :content="decompressResultText"
			@confirm="showDecompressResult = false"></u-modal>
		<nav-bar :value="0"></nav-bar>
	</view>
</template>

<script>
	// import axios from 'axios'; // 确保引入 Axios
	const axios = require('axios')
	import navBar from '@/components/common/nav'
	import search from '@/components/common/search'
	import {
		insertTestData
	} from '@/util/testData.js'
	import {
		mapState,
		mapMutations
	} from 'vuex'
	import {
		openDatabase,
		selectSql,
		isOpenDatabase,
		closeDatabase,
	} from '@/util/sqliteHelper.js'
	import initStaticData from '@/util/initStaticData'
	import store from '@/store/index'

	const path = plus.io.convertLocalFileSystemURL('_doc').split('/0')[1]
	export default {
		components: {
			navBar,
			search,
		},
		data() {
			return {
				data: {},
				// 修改密码
				model: {
					repassword1: '',
					repassword2: '',
				},
				show: false,
				showDirModal: false,
				showDecompressResult: false,
				decompressResultText: '',
				dirModalTitle: '文件放置路径',
				dirContent: path,
			}
		},
		mounted() {
			initStaticData().then(() => {
				if (!isOpenDatabase()) {
					openDatabase()
						.then(() => {
							this.readCoverNumbers()
						})
						.catch((e) => {
							console.error('打开DB失败：', e)
						})
				} else {
					this.readCoverNumbers()
				}
			})
		},
		onShow() {
			//uni.$model("task",(m)=>{m.find(['id'],(err,results)=>{console.log(err);console.log(results);if(!err) console.log('增加成功');});})
			//uni.$model("task",(m)=>{m.insert({id:11,content:"test"},(err,results)=>{ if(!err) console.log('增加成功');});})
		},
		methods: {
			...mapMutations(['emptyUserInfo']),
			logout: function() {
				this.emptyUserInfo(store.state.$userInfo)
				uni.redirectTo({
					url: '/pages/index/login',
				})
			},
			readCoverNumbers() {
				const data = {}
				selectSql('select * from tjinfo').then((res) => {
					try {
						res.forEach((item) => {
							data[item.type] = item['count']
						})
						data.cableSection = parseInt(data.cableSection)
						this.data = data

						const exportTime = res.find((item) => item['id'] === 'exportTime')
						if (exportTime && exportTime.type) {
							this.data.exportTime = exportTime.type
						}
					} catch (error) {
						console.error(error)
					}
				})
			},
			showZipPath() {
				this.showDirModal = true
				this.dirModalTitle = '文件放置路径'
				this.dirContent = path
			},

			// lineImportData() {
			// 	uni.navigateTo({
			// 		url:'/pages/index/select-project'
			// 	})
			// },
			//下载任务
			async importOnLineFileData() {
				const taskId = '1845793414077911042'; // 替换为你的任务ID
				const url = `http://cable.auto-sense.com.cn:19527/api/site/task/export-program-task?taskId=${taskId}`;

				try {
					const response = await axios({
						url,
						method: 'GET',
						responseType: 'blob', // 指定响应类型为 Blob
						headers: {
							'Content-Type': 'application/json',
							// 其他需要的头部信息
						}
					});

					const urlBlob = window.URL.createObjectURL(new Blob([response.data])); // 创建 Blob URL
					const a = document.createElement('a'); // 创建一个链接元素
					a.href = urlBlob;
					a.download = 'downloaded.zip'; // 设置下载文件名
					document.body.appendChild(a); // 将链接元素添加到 DOM
					a.click(); // 触发点击事件以下载文件
					a.remove(); // 下载后移除链接元素
					window.URL.revokeObjectURL(urlBlob); // 释放 Blob URL
				} catch (error) {
					console.error('Error downloading the file:', error);
				}
			},

			// 下载文件的逻辑
			startDownload(apiUrl, dirPath, fileName) {
				const fs = uni.getFileSystemManager();

				// 创建下载任务
				const downloadTask = uni.downloadFile({
					url: apiUrl,
					filePath: `${dirPath}${fileName}`, // 文件保存路径
					success: (res) => {
						if (res.statusCode === 200) {
							uni.showToast({
								title: '下载成功',
								icon: 'success'
							});
						} else {
							uni.showToast({
								title: '下载失败',
								icon: 'none'
							});
						}
					},
					fail: (err) => {
						console.error('下载失败:', err);
						uni.showToast({
							title: '下载失败，请重试',
							icon: 'none'
						});
					}
				});

				// 监听下载进度
				downloadTask.onProgressUpdate((res) => {
					console.log('下载进度', res.progress);
					// 可以在这里更新下载进度条
				});
			},


			importFileData() {
				//执行异步操作关闭数据库，返回一个promise
				closeDatabase().then(() => {
					// 数据库成功关闭后，开始执行以下操作  
					// 使用 plus.zip.decompress 方法解压 ZIP 文件  
					// 参数说明：  
					// 1. '_doc/cable.zip'：要解压的 ZIP 文件路径（位于应用的私有存储目录 _doc/ 下）  
					// 2. '_doc/cable/'：解压后的文件存放的目标目录  
					// 3. 成功回调函数：解压成功后执行  
					// 4. 失败回调函数：解压失败时执行  
					plus.zip.decompress(
						'_doc/cable.zip', // ZIP 文件路径  
						'_doc/cable/', // 解压目标目录
						() => {
							// 解压成功后的操作  
							// 设置数据属性，用于在界面上显示解压成功的结果 
							this.showDecompressResult = true
							this.decompressResultText = '数据导入成功'
							openDatabase().then(() => {
								// 调用 readCoverNumbers 方法，可能是用来读取解压后的数据或执行其他操作 
								this.readCoverNumbers()
							})
						},
						(error) => {
							console.error('解压失败', error)
							this.showDecompressResult = true //
							this.decompressResultText =
								'数据导入失败，请检查数据压缩包是否放到了指定文件夹内'
						}
					)
				})
			},
			loadTestData: function() {
				insertTestData().then((res) => {
					console.log('[loadTestData]', res)
				})
			},
			initSqliteDb() {
				return new Promise((resolve, reject) => {
					plus.io.resolveLocalFileSystemURL(
						'_www/static/cable.db',
						function(entry) {
							plus.io.resolveLocalFileSystemURL('_doc', function(root) {
								entry.copyTo(
									root,
									'cable.db',
									function(entryCode) {
										console.log('拷贝成功')
										resolve(entryCode)
									},
									function(e) {
										// 拷贝失败是因为之前已经拷过了，文件名被占用
										resolve('已经拷贝过')
									}
								)
							})
						},
						function(e) {
							console.error('读取db文件失败，失败原因：', e)
							reject(e)
						}
					)
				})
			},
			modify() {
				this.show = true
			},
			close() {
				this.show = false
			},
			reSubmit() {
				this.$refs.form
					.validate()
					.then(() => {
						const {
							repassword1,
							repassword2
						} = this.model
						if (!repassword1) {
							uni.$u.toast('请输入密码')
							return
						}
						if (repassword1 !== repassword2) {
							uni.$u.toast('两次输入的密码不一致')
							return
						}
						const reg = /^[0-9a-zA-Z]{6,20}$/
						if (!reg.test(repassword1) || !reg.test(repassword2)) {
							uni.$u.toast('请输入6-20位长度密码')
							return
						}
						selectSql(
							`update user set pwd="${repassword1}" where usename="admin"`
						).then((res) => {
							console.log('update result:', res)
							uni.showToast({
								title: '修改密码成功',
								icon: 'success',
								duration: 2000,
							})
							this.$refs.form.resetFields()
							this.show = false
						})
					})
					.catch((e) => {})
			},
		},
	}
</script>

<style lang="scss">
	page {
		height: 100%;
		// background: linear-gradient(to top, #ffffff, #139C99, #139C99);
		background: #139c99;
	}
</style>

<style lang="scss" scoped>
	@import '@/style/config.scss';

	.container {
		//background: linear-gradient(to top, #ffffff, #a2c4c9, #7ab6bf);
		/* #ifndef APP-NVUE */
		padding-top: 2rem;

		/* #endif */
		.input-item {
			margin-bottom: 1rem;
		}

		.space1 {
			margin-left: 1rem;
			padding-right: 2rem 1rem;
		}

		.btn {
			background-color: #139c99;
			color: #fff;
		}

		.row {
			display: flex;
			justify-content: space-evenly;
			padding: 1rem 1rem;
			width: 70%;
			margin: 0 auto;

			&.row-underline {
				border-bottom: 1px solid #ddd;
			}

			.space {
				margin-left: 1rem;
				border-left: solid 1px #ddd;
				padding-right: 2rem 1rem;
			}

			.item {
				flex: 1;
				width: 5rem;
				display: flex;
				flex-direction: column;
				align-content: center;
				justify-content: center;
				color: #ffffff;

				.value {
					font-weight: bold;
					text-align: center;
					margin-bottom: 0.5rem;

					.data {
						font-size: 1.2rem;
						padding-right: 0.4rem;
					}
				}

				.name {
					font-weight: bold;
					text-align: center;
					font-size: 1rem;
				}
			}
		}
	}

	.export-time {
		color: #dfdfdf;
	}

	// fix: modal内容中英文不换行
	/deep/ .u-modal__content {
		word-break: break-all;
	}
</style>